﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MYSMRM.Model;
using System.Data;
using MYSMRM.Manager.Interface;
using MYSMRM.Common;

namespace MYSMRM.Web.QS
{

    public partial class TopicDetail : System.Web.UI.Page
    {
        private bool _bNew = false;

        private int _iTopicID = -1;
        private QSTopic _topic;
        private DataTable _dtQuestion;

        public IQSTopicManager TopicManager { get; set; }
        public IQSQuestionManager OptionManager { get; set; }


        #region Page Events
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["I_ID"] == null)
                {
                    _bNew = true;
                }
                else
                {
                    _iTopicID = Convert.ToInt32(Request.QueryString["I_ID"]);
                }

                InitData();
                FillFields();

                ViewState["TopicID"] = _iTopicID;
                ViewState["dtQuestion"] = _dtQuestion;
            }
            else
            {
                _iTopicID = Convert.ToInt32(ViewState["TopicID"]);
                _dtQuestion = ViewState["dtQuestion"] as DataTable;
            }
        }

        protected void lbtn_Add_Click(object sender, EventArgs e)
        {
            //if (_iTopicID == -1)
            //    return;
            #region save topic detail
            _topic = new QSTopic();
            _topic.Title = txt_Title.Text;

            _topic.StartDate = Convert.ToDateTime(txt_StartDate.Text + " " + txt_StartTime.Text);
            _topic.EndDate = Convert.ToDateTime(txt_EndDate.Text + " " + txt_EndTime.Text);

            _topic.Anonymity = cb_Anonymity.Checked;
            _topic.AutoClose = cb_AllowAutoClose.Checked;
            _topic.SendEmail = cb_SendEmail.Checked;
            _topic.EmailAddress = txt_EmailAddress.Text;

            _topic.CreateDate = DateTime.Now;
            _topic.Creator = ""; // TODO: use the current operator
            #endregion
            _topic.QuestionList=new List<QSQuestion>();//shine 20130524
            #region shine need attention
            //List<QSQuestion> ql = new List<QSQuestion>();
            //if (_dtQuestion != null)
            //{
            //    foreach (var items in _dtQuestion.AsEnumerable())
            //    {
            //        // items.SetField<int>("I_TOPIC_ID",-1);
            //        QSQuestion q = new QSQuestion();
            //        q.Question = items.Field<string>("S_QUESTION");
            //        q.Sequence = items.Field<int>("I_SEQUENCE");
            //        q.MultiSelect = items.Field<bool>("B_MULTI_SELECT");
            //        q.LastUpdater = "login user";
            //        q.LastUpdateDate = DateTime.Now;
            //        q.Creator = "login user";
            //        q.CreateDate = DateTime.Now;
            //        q.Topic = _topic;
            //        ql.Add(q);
            //    }
            //}
            //_topic.AddList(ql);
            #endregion
             _topic.AddList(DataTable2Object.ConvertToList<QSQuestion>(_dtQuestion));
            
            #region save option detail

            #endregion

            // save to database
            try
            {
                TopicManager.Save(_topic);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
                // TODO: record this exception with log4net
            }
        }

        protected void lbtn_Save_Click(object sender, EventArgs e)
        {
            //List<QSOption> lo = DataTable2Object.ConvertToList<QSOption>(_dtOption);

            _topic = TopicManager.Get(_iTopicID);

            if (_topic != null)
            {
                _topic.ID = _iTopicID;
                _topic.Title = txt_Title.Text;

                _topic.StartDate = Convert.ToDateTime(txt_StartDate.Text + " " + txt_StartTime.Text);
                _topic.EndDate = Convert.ToDateTime(txt_EndDate.Text + " " + txt_EndTime.Text);

                _topic.Anonymity = cb_Anonymity.Checked;
                _topic.AutoClose = cb_AllowAutoClose.Checked;
              
                _topic.SendEmail = cb_SendEmail.Checked;
                _topic.EmailAddress = txt_EmailAddress.Text;

                _topic.QuestionList.Clear();
                _topic.AddList(DataTable2Object.ConvertToList<QSQuestion>(_dtQuestion));

                // update to database
                try
                {
                    TopicManager.Update(_topic);
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                    // TODO: record this exception with log4net
                }
            }
        }

        protected void lbtn_Cancel_Click(object sender, EventArgs e)
        {
            this.Clear();
            Response.Redirect("..//QS//TopicList.aspx");
        }
        #endregion

        #region Option Events
        protected void lbtn_AddQuestion_Click(object sender, EventArgs e)
        {
            
            if (_iTopicID > 0)
              {
                
                if (txt_Question.Text.Trim() != "")
                {
                   // Response.Redirect("..//QS//QuestionDetail.aspx?TopicID=" + _iTopicID.ToString());
            //        // InitOptionTable();
            //        //Response.Redirect("..//QS//OptionDetail.aspx?TopidID=" + _iTopicID.ToString());

                    DataRow dr = _dtQuestion.NewRow();
                    dr["I_ID"] = GetLargestQuestionID() + 1;
                    dr["I_TOPIC_ID"] = _iTopicID;
                    dr["S_QUESTION"] = txt_Question.Text;
                    //dr["B_DELETED"] = false;
                    dr["I_SEQUENCE"] = txt_Sequence.Text;//shine
                    dr["B_MULTI_SELECT"] = cb_MultiSelect.Checked;
                    dr["S_LAST_UPDATER"] = "";
                    dr["D_LAST_UPDATE_DATE"] = DateTime.Now;
                    dr["S_CREATOR"] = "";
                    dr["D_CREATEDATE"] = DateTime.Now;
                    _dtQuestion.Rows.Add(dr);

                    ViewState["dtQuestion"] = _dtQuestion;

                    BindQuestion();
                }
            }
        }

        private int GetLastQuestionID()
        {
            int lastQID = -1;
            return lastQID;
        }

        protected void gv_Questions_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            _dtQuestion.Rows.RemoveAt(e.RowIndex);
            _dtQuestion.AcceptChanges();
            ViewState["dtQuestion"] = _dtQuestion;
            BindQuestion();
        }

        protected void gv_Questions_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gv_Questions.EditIndex = e.NewEditIndex;
            BindQuestion();
            int questionID = Convert.ToInt32(gv_Questions.DataKeys[e.NewEditIndex].Value);
           // int it = e.NewEditIndex;
            //string t = gv_Questions.Rows[e.NewEditIndex].Cells[0].Text.ToString().Trim();
           // string t = gv_Questions.DataKeys[e.NewEditIndex].Value.ToString();
            Response.Redirect("..//QS//QuestionDetail.aspx?Topic=" + txt_Title.Text + "&I_ID=" + questionID.ToString() + "&TopicID=" + _iTopicID.ToString());
        }

        protected void gv_Questions_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gv_Questions.EditIndex = -1;
            BindQuestion();
        }

        protected void gv_Questions_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            int ID = Convert.ToInt32(gv_Questions.DataKeys[e.RowIndex].Value);
            foreach (DataRow dr in _dtQuestion.Rows)
            {
                if (Convert.ToInt32(dr["I_ID"]) == ID)
                {
                    dr["S_OPTION"] = Server.HtmlDecode(((TextBox)gv_Questions.Rows[e.RowIndex].Cells[2].Controls[0]).Text.ToString());
                    dr["S_LAST_UPDATER"] = "";
                    dr["D_LAST_UPDATE_DATE"] = DateTime.Now;
                    _dtQuestion.AcceptChanges();
                    ViewState["dtOption"] = _dtQuestion;
                    gv_Questions.EditIndex = -1;
                    break;
                }
            }

            BindQuestion();
        }

        protected void gv_Questions_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
                {
                    ((LinkButton)e.Row.Cells[6].Controls[0]).Attributes["onclick"] = "if(!confirm('你真的要删除" + e.Row.Cells[3].Text + "这条记录么?'))return false;";
                }
            }
        }
        #endregion

        #region Methods
        /// <summary>
        /// Initial data for this page
        /// </summary>
        private void InitData()
        {
            // TODO: Initial data for this page
            if (_iTopicID >= 0)
            {
                _topic = TopicManager.Load(_iTopicID);

                _dtQuestion = DataTable2Object.ConvertToDataTableFromList(_topic.QuestionList);
            }
            else
            {
                InitQuestionTable();
            }
            // TODO: initial options for topic
            //InitTestData();
        }

        private void FillFields()
        {
            if (_topic != null)
            {
                txt_Title.Text = _topic.Title;

                txt_StartDate.Text = _topic.StartDate.ToShortDateString();
                txt_StartTime.Text = _topic.StartDate.ToShortTimeString();
                txt_EndDate.Text = _topic.EndDate.ToShortDateString();
                txt_EndTime.Text = _topic.EndDate.ToShortTimeString();

                cb_Anonymity.Checked = _topic.Anonymity;
                cb_AllowAutoClose.Checked = _topic.AutoClose;
                
                cb_SendEmail.Checked = _topic.SendEmail;
                txt_EmailAddress.Text = _topic.EmailAddress;
            }

            if (_dtQuestion != null)
            {
                gv_Questions.DataSource = _dtQuestion;
                gv_Questions.DataBind();
            }
        }

        private void InitQuestionTable()
        {
            if (_dtQuestion == null)
            {
                _dtQuestion = new DataTable();
                _dtQuestion.Columns.Add("I_ID");
                _dtQuestion.Columns.Add("I_TOPIC_ID");
                _dtQuestion.Columns.Add("S_QUESTION");
                _dtQuestion.Columns.Add("I_SEQUENCE");
                _dtQuestion.Columns.Add("B_MULTI_SELECT");
                _dtQuestion.Columns.Add("S_LAST_UPDATER");
                _dtQuestion.Columns.Add("D_LAST_UPDATE_DATE");
                _dtQuestion.Columns.Add("S_CREATOR");
                _dtQuestion.Columns.Add("D_CREATEDATE");
            }
        }

        /// <summary>
        /// Clear all temp data for this page
        /// </summary>
        private void Clear()
        {
            // TODO: Clear all temp data for this page
        }

        private void BindQuestion()
        {
            gv_Questions.DataSource = _dtQuestion;
            gv_Questions.DataKeyNames = new string[] { "I_ID" };
            gv_Questions.DataBind();
        }

        private int GetLargestQuestionID()
        {
            int maxResult = -1;
            if (_dtQuestion.Rows.Count > 0)
            {
                maxResult = _dtQuestion.AsEnumerable().Select(t => t.Field<int>("I_ID")).Max();
            }
            #region 以前的，shine 20130524注释
            //int iResult = -1;
            //for (int i = 0; i < _dtQuestion.Rows.Count; i++)
            //{
            //    if (Convert.ToInt32(_dtQuestion.Rows[i]["I_ID"]) > iResult)
            //    {
            //        iResult = Convert.ToInt32(_dtQuestion.Rows[i]["I_ID"]);
            //    }
            //}
            //return iResult;
            #endregion
            return maxResult;
        }
        #endregion
    }
   
}